﻿using System;
using System.IO;
using AudioCore.Biz;
using AudioCore.Entity;
using AudioBook.AudioManagement.Util;
using AudioCore.Common;

namespace AudioBook.AudioManagement.AudioManage
{
    public partial class AudioFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string strPartID = Request.QueryString[GUIConstants.Common.ID_QUERY];
            int idQuery = 0;
            if (int.TryParse(strPartID, out idQuery))
            {
                ArticlePartBiz bizArticlePart = new ArticlePartBiz();
                ArticlePartEntity enArticlePart = bizArticlePart.GetArticlePartByID(idQuery);
                if (enArticlePart != null)
                {
                    WriteAudio(enArticlePart.ArticleID, enArticlePart.ArticlePartID);
                }
            }
        }

        private void WriteAudio(int articleID, int partID)
        {
            string audioFile = GlobalParam.DataFolder + Constant.AUDIO_FOLDER + articleID.ToString() + "\\" +
                partID.ToString() + "_000" + Constant.AUDIO_EXTENSION;

            WriteFile(audioFile);
        }

        /// <summary>
        /// Write down the content of a file to the client
        /// </summary>
        /// <param name="filePath">Physical path of the file</param>
        private void WriteFile(string filePath)
        {
            if (File.Exists(filePath))
            {
                string fileName = filePath.Substring(filePath.LastIndexOf('\\') + 1);

                Response.Clear();
                Response.ContentType = "audio/mpeg3";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                Response.WriteFile(filePath);
                Response.Flush();
            }
            else
            {
                Response.Write("File not found: " + filePath);
            }
        }
    }
}
